package org.example.springboot.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.example.springboot.common.Result;
import org.example.springboot.entity.BookCategory;
import org.example.springboot.service.BookCategoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 图书分类管理控制器
 */
@Tag(name="图书分类管理接口")
@RestController
@RequestMapping("/book/category")
public class BookCategoryController {
    private static final Logger LOGGER = LoggerFactory.getLogger(BookCategoryController.class);
    
    @Resource
    private BookCategoryService bookCategoryService;
    
    @Operation(summary = "获取所有分类")
    @GetMapping("/all")
    public Result<?> getAllCategories() {
        List<BookCategory> categories = bookCategoryService.getAllCategories();
        return Result.success(categories);
    }
    
    @Operation(summary = "获取分类树结构")
    @GetMapping("/tree")
    public Result<?> getCategoryTree() {
        List<BookCategory> categoryTree = bookCategoryService.getCategoryTree();
        return Result.success(categoryTree);
    }
    
    @Operation(summary = "根据ID获取分类")
    @GetMapping("/{id}")
    public Result<?> getCategoryById(@PathVariable Long id) {
        BookCategory category = bookCategoryService.getCategoryById(id);
        return Result.success(category);
    }
    
    @Operation(summary = "添加分类")
    @PostMapping("/add")
    public Result<?> addCategory(@RequestBody @Valid BookCategory category) {
        Long categoryId = bookCategoryService.addCategory(category);
        return Result.success("添加成功", categoryId);
    }
    
    @Operation(summary = "更新分类")
    @PutMapping("/{id}")
    public Result<?> updateCategory(@PathVariable Long id, @RequestBody @Valid BookCategory category) {
        bookCategoryService.updateCategory(id, category);
        return Result.success("更新成功");
    }
    
    @Operation(summary = "删除分类")
    @DeleteMapping("/{id}")
    public Result<?> deleteCategory(@PathVariable Long id) {
        bookCategoryService.deleteCategory(id);
        return Result.success("删除成功");
    }
    
    @Operation(summary = "获取有图书的分类并按照图书数量排序")
    @GetMapping("/with-books")
    public Result<?> getCategoriesWithBooks(@RequestParam(required = false) Integer limit) {
        List<Map<String, Object>> categories = bookCategoryService.getCategoriesWithBookCount(limit);
        return Result.success(categories);
    }
} 